<template>
    <view class="entry-apply-container">
        <view v-if="isResubmit" class="reject-tip">拒绝原因：{{ rejectReason }}</view>
        <view class="title">商户入驻申请</view>
        <form @submit.prevent="handleSubmit">
            <view class="form-item">
                <text>商户名称</text>
                <input v-model="form.name" placeholder="请输入商户名称" />
            </view>
            <view class="form-item">
                <text>联系电话</text>
                <input v-model="form.phone" placeholder="请输入联系电话" />
            </view>
            <view class="form-item">
                <text>商户地址</text>
                <input v-model="form.address" placeholder="请输入商户地址" />
            </view>
            <view class="form-item">
                <view class="field-header">
                    <text>商户号</text>
                    <text class="required-tip">（需联系客服获取）</text>
                </view>
                <input v-model="form.subMchid" placeholder="请输入商户号" />
                <view class="contact-service">
                    <text class="service-tip">商户号需要联系平台客服获取</text>
                    <button class="contact-btn" @click.prevent="contactService">联系客服</button>
                </view>
            </view>
            <view class="form-item">
                <text>所属食堂（可选）</text>
                <picker :range="canteenList" range-key="name"
                    :value="canteenList.findIndex(c => c.id == form.canteenId)" @change="handleCanteenChange">
                    <view class="picker-view custom-picker" :class="{ 'picker-selected': !!form.canteenId }">
                        <text :class="{ 'placeholder': !form.canteenId }">
                            {{canteenList.find(c => c.id == form.canteenId)?.name || '请选择食堂'}}
                        </text>
                        <text class="arrow">&#9662;</text>
                    </view>
                </picker>
            </view>
            <view class="form-item">
                <text>商户Logo</text>
                <button @click.prevent="chooseImage('logo')">上传Logo</button>
                <image v-if="form.logo" :src="form.logo" class="preview-img" />
            </view>
            <view class="form-item">
                <text>营业执照图片</text>
                <button @click.prevent="chooseImage('licenseImageList')">上传营业执照</button>
                <view class="img-list">
                    <block v-for="(img, idx) in form.licenseImageList" :key="img">
                        <image :src="img" class="preview-img" />
                        <text class="remove-img" @click="removeImage('licenseImageList', idx)">×</text>
                    </block>
                </view>
            </view>
            <view class="form-item">
                <text>店内照片</text>
                <button @click.prevent="chooseImage('shopImageList')">上传店内照片</button>
                <view class="img-list">
                    <block v-for="(img, idx) in form.shopImageList" :key="img">
                        <image :src="img" class="preview-img" />
                        <text class="remove-img" @click="removeImage('shopImageList', idx)">×</text>
                    </block>
                </view>
            </view>
            <view class="form-item">
                <text>商户描述</text>
                <textarea v-model="form.description" placeholder="请输入商户描述" />
            </view>
            <button class="submit-btn" type="primary" formType="submit">提交申请</button>
        </form>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { submitMerchantApply, getCanteenList, getLatestMerchantApply } from '@/api/user'
import { uploadToOSS, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss'
import { onLoad } from '@dcloudio/uni-app'

const userStore = useUserStore()
const canteenList = ref([])
const isResubmit = ref(false)
const rejectReason = ref('')

const form = ref({
    name: '',
    phone: '',
    address: '',
    subMchid: '',
    logo: '',
    licenseImage: '',
    licenseImageList: [],
    shopImage: '',
    shopImageList: [],
    description: '',
    canteenId: ''
})

onLoad(async (query) => {
    isResubmit.value = query.resubmit === '1'
    rejectReason.value = decodeURIComponent(query.reason || '')
    if (isResubmit.value && userStore.userInfo?.id) {
        try {
            const { data } = await getLatestMerchantApply({ merchantUserId: userStore.userInfo.id })
            if (data) {
                form.value.name = data.name || ''
                form.value.phone = data.phone || ''
                form.value.address = data.address || ''
                form.value.subMchid = data.subMchid || ''
                form.value.logo = data.logo || ''
                form.value.licenseImageList = data.licenseImage ? data.licenseImage.split(',') : []
                form.value.shopImageList = data.shopImage ? data.shopImage.split(',') : []
                form.value.description = data.description || ''
                form.value.canteenId = data.canteenId || ''
            }
        } catch (e) {
            // ignore
        }
    }
})

onMounted(async () => {
    try {
        const { data } = await getCanteenList()
        canteenList.value = data
    } catch (e) {
        canteenList.value = []
    }
    await fetchAndScheduleStsToken()
})

onUnmounted(() => {
    clearStsTokenTimer()
})

function handleCanteenChange(e) {
    const idx = e.detail.value
    if (canteenList.value[idx]) {
        form.value.canteenId = canteenList.value[idx].id
    } else {
        form.value.canteenId = ''
    }
}

/**
 * 选择图片并上传到OSS，支持单图和多图
 * @param {String} field 表单字段名
 */
async function chooseImage(field) {
    const isMulti = field === 'licenseImageList' || field === 'shopImageList'
    uni.chooseImage({
        count: isMulti ? 6 : 1,
        success: async (res) => {
            try {
                uni.showLoading({ title: '上传中...' })
                if (isMulti) {
                    // 多图上传
                    const uploadPromises = res.tempFilePaths.map(path => uploadToOSS(path, field))
                    const urls = await Promise.all(uploadPromises)
                    form.value[field] = form.value[field].concat(urls).slice(0, 6)
                } else {
                    // 单图上传
                    const url = await uploadToOSS(res.tempFilePaths[0], field)
                    form.value[field] = url
                }
                uni.hideLoading()
                uni.showToast({ title: '上传成功', icon: 'success' })
            } catch (e) {
                console.log(e)
                uni.showToast({ title: '上传失败', icon: 'none' })
            } finally {
                uni.hideLoading()
            }
        }
    })
}

function removeImage(field, idx) {
    form.value[field].splice(idx, 1)
}

function validateForm() {
    if (!form.value.name.trim()) {
        uni.showToast({ title: '请输入商户名称', icon: 'none' });
        return false;
    }
    if (!form.value.phone.trim()) {
        uni.showToast({ title: '请输入联系电话', icon: 'none' });
        return false;
    }
    if (!/^1[3-9]\d{9}$/.test(form.value.phone.trim())) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' });
        return false;
    }
    if (!form.value.address.trim()) {
        uni.showToast({ title: '请输入商户地址', icon: 'none' });
        return false;
    }
    if (!form.value.subMchid.trim()) {
        uni.showToast({ title: '请输入商户号', icon: 'none' });
        return false;
    }
    if (!form.value.logo) {
        uni.showToast({ title: '请上传商户Logo', icon: 'none' });
        return false;
    }
    if (!form.value.licenseImageList.length) {
        uni.showToast({ title: '请上传营业执照', icon: 'none' });
        return false;
    }
    if (!form.value.shopImageList.length) {
        uni.showToast({ title: '请上传店内照片', icon: 'none' });
        return false;
    }
    if (!form.value.description.trim()) {
        uni.showToast({ title: '请输入商户描述', icon: 'none' });
        return false;
    }
    return true;
}

function contactService() {
    uni.showModal({
        title: '联系客服',
        content: '请联系平台客服获取商户号\n\n客服电话：15910519758\n客服微信：15910519758\n工作时间：9:00-18:00',
        showCancel: false,
        confirmText: '我知道了'
    })
}

async function handleSubmit() {
    if (!userStore.userInfo?.id) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
    }
    if (!validateForm()) return;
    const formData = {
        ...form.value,
        merchantUserId: userStore.userInfo.id,
        licenseImage: form.value.licenseImageList.join(','),
        shopImage: form.value.shopImageList.join(',')
    }
    try {
        await submitMerchantApply(formData)
        uni.showToast({ title: '提交成功，等待审核', icon: 'success' })
        setTimeout(() => {
            uni.redirectTo({ url: '/pages/entry/pending' })
        }, 1000)
    } catch (e) {
        uni.showToast({ title: e.message || '提交失败', icon: 'none' })
    }
}
</script>

<style lang="scss" scoped>
.entry-apply-container {
    padding: 32px 20px;
}
.reject-tip {
    color: #d9534f;
    font-size: 16px;
    margin-bottom: 12px;
    text-align: center;
    font-weight: bold;
}

.title {
    font-size: 22px;
    font-weight: bold;
    margin-bottom: 24px;
    text-align: center;
}

.form-item {
    margin-bottom: 18px;
    display: flex;
    flex-direction: column;
}

input,
textarea {
    border: 1px solid #eee;
    border-radius: 6px;
    padding: 8px;
    margin-top: 6px;
}

.custom-picker {
    display: flex;
    align-items: center;
    border: 1px solid #eee;
    border-radius: 6px;
    padding: 10px 12px;
    background: #fafafa;
    margin-top: 6px;
    position: relative;
    min-height: 40px;
    color: #888;
    font-size: 16px;
    cursor: pointer;
}

.picker-selected {
    color: #222;
    background: #fff;
    border-color: #ccc;
}

.custom-picker .arrow {
    margin-left: auto;
    font-size: 18px;
    color: #bbb;
}

.placeholder {
    color: #bbb;
}

.img-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}

.preview-img {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    position: relative;
}

.remove-img {
    position: absolute;
    margin-left: -18px;
    margin-top: -8px;
    color: #fff;
    background: #d9534f;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    text-align: center;
    line-height: 18px;
    font-size: 14px;
    cursor: pointer;
}

.field-header {
    display: flex;
    align-items: center;
    gap: 8px;
}

.required-tip {
    color: #ff6b35;
    font-size: 12px;
    font-weight: normal;
}

.contact-service {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 8px;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.service-tip {
    color: #6c757d;
    font-size: 12px;
    flex: 1;
}

.contact-btn {
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    font-size: 12px;
    margin: 0;
    min-height: auto;
    line-height: 1.2;
}

.contact-btn:active {
    background: #0056b3;
}

.submit-btn {
    width: 100%;
    margin-top: 24px;
    font-size: 18px;
}
</style>